package com.hiwhitley.leetcode.easy;

import com.hiwhitley.base.ListNode;

import java.util.Stack;

/**
 * Created by hiwhitley on 17-2-28.
 */
public class RemoveLinkedListElements_203 {
    public ListNode removeElements1(ListNode head, int val) {
        if (head == null) {
            return head;
        }

        Stack<ListNode> stack = new Stack<>();
        while (head != null) {
            if (head.val != val) {
                stack.push(head);
            }
            head = head.next;
        }

        while (!stack.isEmpty()) {
            stack.peek().next = head;
            head = stack.pop();
        }
        return head;
    }

    public ListNode removeElements2(ListNode head, int val) {
        while (head != null) {
            if (head.val != val) {
                break;
            }
            head = head.next;
        }

        ListNode pre = head;
        ListNode next = head;
        while (next != null) {
            if (next.val == val) {
                pre.next = next.next;
            } else {
                pre = next;
            }

            next = next.next;
        }

        return head;
    }
}
